class SessionController < ApplicationController
  def login
    
  end

  def auth
    authorized_user = User.authenticate(params[:login_email],params[:login_password])

    if authorized_user
      flash[:message] = t('Wow Welcome again you logged in as')+"#{authorized_user.email}"
      session[:user] = authorized_user

      redirect_to(:controller => 'default', :action => 'index')
    else
      flash[:notice] = t('Invalid Username or Password')
      flash[:color]= "invalid"
      render "login"
    end
  end

  def logout
    session.delete(:user)
    redirect_to(:controller => 'default', :action => 'index')
  end

  def editpassword
  end

  def updatepassword
    
  end

  def forgotpassword
  end

  def resetpassword
    email = params[:email_add]
    id_number = params[:id_number_add]
    #if (email == "ngochoatong@gmail.com") 
    
    if email
      user = User.find_by_email(email)
      if user
        if user.idnumber == id_number
          resetpassword = user.reset_password()
          user.password = resetpassword
          user.save
          Notifier.google_message(email,resetpassword).deliver
          
          flash[:message] = "Your password has been sent to your email, please check your email!"
          redirect_to root_url
        else
          flash[:notice] = "The informations that you typed are wrong!"
          redirect_to :controller => 'session', :action => 'resetpassword'
        end
      else
        flash[:notice] = "There is no account with email "+email
        redirect_to(:controller => 'session', :action => 'resetpassword')
      end
   end
    
  end
  
  def ban
    
  end
  
  def changepassword
    user = session[:user];
    old_password_type = params[:old_password]
    new_password = params[:new_password]
    retype_password = params[:retype_password]
    
    if(user.match_password(old_password_type))
        if new_password ==retype_password
          if new_password.length >= 8
            user.password = new_password
            user.save
            flash[:message] = "You have just changed password successfully"
            redirect_to root_url
          else
             flash[:notice] = "Password at least 8 characters"          
              redirect_to :controller => 'session',:action => 'updatepassword'
          end
        else
            flash[:notice] = "Password doesn't match confirm password"          
            redirect_to :controller => 'session',:action => 'updatepassword'
        end
    else
      flash[:notice] = "Your old password is incorrect"
      redirect_to :controller => 'session',:action => 'updatepassword'
    end
  end
  
  def borrowbook 
    
  end
  
  def profile

  end
  
end
